/*==============================================================================
  项目名称: Auto2数据集高级分析脚本
  创建日期: 2025-10-26
  描述: 使用Stata内置auto2.dta数据集进行多样化数据分析
        包含高级统计分析、多种可视化和多格式输出
==============================================================================*/

* 清空内存和关闭所有日志
clear all
set more off
capture log close

* 开启日志记录
log using "auto2_analysis_log.smcl", replace

/*------------------------------------------------------------------------------
  1. 数据加载和初步探索
------------------------------------------------------------------------------*/
* 加载Stata内置的auto2数据集
webuse auto2, clear

* 数据基本信息
describe
codebook, compact

* 查看前20条记录
list in 1/20, separator(5)

/*------------------------------------------------------------------------------
  2. 创建输出目录
------------------------------------------------------------------------------*/
capture mkdir "../dataset"
capture mkdir "../dataset/auto2_output"
capture mkdir "../dataset/auto2_output/graphs"
capture mkdir "../dataset/auto2_output/tables"
capture mkdir "../dataset/auto2_output/latex"
capture mkdir "../dataset/auto2_output/excel"

/*------------------------------------------------------------------------------
  3. 数据清理和变量工程
------------------------------------------------------------------------------*/
* 检查缺失值
misstable summarize
misstable patterns

* 处理缺失值
egen rep78_mode = mode(rep78)
replace rep78 = rep78_mode if missing(rep78)
drop rep78_mode

* 生成新变量
* 1. 价格对数
generate log_price = log(price)
label variable log_price "价格对数"

* 2. 重量（千克）
generate weight_kg = weight * 0.453592
label variable weight_kg "重量（千克）"

* 3. 油耗（升/100公里）
generate fuel_consumption = 235.215 / mpg
label variable fuel_consumption "油耗（升/100公里）"

* 4. 价格分位数分组
xtile price_quartile = price, nquantiles(4)
label variable price_quartile "价格四分位数"

* 5. 性能指标：马力重量比
generate power_weight_ratio = (turn / weight) * 1000
label variable power_weight_ratio "性能指标"

* 6. 豪华车标识（高价格+进口）
generate luxury = (price > 10000 & foreign == 1)
label variable luxury "豪华车"

* 7. 经济型车（低价格+高油耗）
generate economy = (price < 5000 & mpg > 25)
label variable economy "经济型车"

* 8. 车型大小分类
generate size_category = 1 if weight < 2500
replace size_category = 2 if weight >= 2500 & weight < 3500
replace size_category = 3 if weight >= 3500 & !missing(weight)
label define size_lbl 1 "小型" 2 "中型" 3 "大型"
label values size_category size_lbl
label variable size_category "车型大小"

* 添加值标签
label define foreign_lbl 0 "国产" 1 "进口"
label values foreign foreign_lbl

/*------------------------------------------------------------------------------
  4. 描述性统计分析
------------------------------------------------------------------------------*/
* 全样本描述性统计
summarize price mpg weight length turn displacement gear_ratio, detail

* 按产地分组统计
bysort foreign: summarize price mpg weight

* 按车型大小分组统计
bysort size_category: summarize price mpg weight

/*------------------------------------------------------------------------------
  5. 高级统计分析
------------------------------------------------------------------------------*/
* 5.1 T检验：国产车vs进口车价格差异
ttest price, by(foreign)

* 5.2 方差分析：不同车型大小的价格差异
oneway price size_category, tabulate

* 5.3 卡方检验：产地与车型大小的关系
tabulate foreign size_category, chi2 expected

* 5.4 相关性分析
correlate price mpg weight length displacement

* 5.5 分位数回归
qreg price mpg weight foreign, quantile(.25)
estimates store qreg25
qreg price mpg weight foreign, quantile(.50)
estimates store qreg50
qreg price mpg weight foreign, quantile(.75)
estimates store qreg75

/*------------------------------------------------------------------------------
  6. 回归分析
------------------------------------------------------------------------------*/
* 6.1 简单线性回归
regress price mpg
estimates store ols1

* 6.2 多元线性回归
regress price mpg weight foreign
estimates store ols2

* 6.3 包含交互项的回归
generate mpg_foreign = mpg * foreign
regress price mpg weight foreign mpg_foreign
estimates store ols3

* 6.4 对数线性回归
regress log_price mpg weight foreign
estimates store log_ols

* 6.5 稳健标准误回归
regress price mpg weight foreign, robust
estimates store robust_ols

/*------------------------------------------------------------------------------
  7. 生成高级可视化图表
------------------------------------------------------------------------------*/
* 图1: 价格分布的核密度估计
kdensity price, normal ///
    title("汽车价格核密度估计") ///
    xtitle("价格 (美元)") ytitle("密度") ///
    note("数据来源: auto2.dta")
graph export "../dataset/auto2_output/graphs/price_kdensity.png", replace

* 图2: 价格对数的直方图
histogram log_price, frequency normal ///
    title("价格对数分布") ///
    xtitle("log(价格)") ytitle("频数")
graph export "../dataset/auto2_output/graphs/log_price_hist.png", replace

* 图3: 按产地和车型大小的价格箱线图
graph box price, over(size_category) over(foreign) ///
    title("不同车型大小和产地的价格分布") ///
    ytitle("价格 (美元)") ///
    asyvars
graph export "../dataset/auto2_output/graphs/price_box_detailed.png", replace

* 图4: 油耗与价格的散点图矩阵
graph matrix price mpg weight length, ///
    half ///
    title("主要变量散点图矩阵")
graph export "../dataset/auto2_output/graphs/scatter_matrix.png", replace

* 图5: 油耗与重量的分组散点图
twoway (scatter mpg weight if foreign==0, mcolor(blue) msymbol(circle)) ///
       (scatter mpg weight if foreign==1, mcolor(red) msymbol(triangle)) ///
       (lfit mpg weight if foreign==0, lcolor(blue) lpattern(dash)) ///
       (lfit mpg weight if foreign==1, lcolor(red) lpattern(dash)), ///
    title("油耗与重量关系（按产地分组）") ///
    xtitle("重量 (磅)") ytitle("每加仑英里数") ///
    legend(order(1 "国产-观测值" 2 "进口-观测值" 3 "国产-拟合线" 4 "进口-拟合线"))
graph export "../dataset/auto2_output/graphs/mpg_weight_grouped.png", replace

* 图6: 价格四分位数的条形图
graph bar (count), over(price_quartile) over(foreign) asyvars ///
    title("价格四分位数分布") ///
    ytitle("车辆数量") ///
    legend(label(1 "国产") label(2 "进口"))
graph export "../dataset/auto2_output/graphs/price_quartile_bar.png", replace

* 图7: 维修记录的堆叠条形图
graph bar (count), over(rep78) over(foreign) asyvars stack ///
    title("维修记录分布（堆叠）") ///
    ytitle("车辆数量")
graph export "../dataset/auto2_output/graphs/repair_stacked.png", replace

* 图8: 价格与油耗的拟合图（带置信区间）
twoway (scatter price mpg, mcolor(navy) msize(small)) ///
       (lfitci price mpg, fcolor(gs14) lcolor(red)), ///
    title("价格与油耗关系（含95%置信区间）") ///
    xtitle("每加仑英里数") ytitle("价格 (美元)") ///
    legend(order(1 "观测值" 2 "拟合线" 3 "95% CI"))
graph export "../dataset/auto2_output/graphs/price_mpg_ci.png", replace

* 图9: 残差图
quietly regress price mpg weight foreign
predict residuals, residuals
predict fitted, xb
twoway (scatter residuals fitted, mcolor(blue) msize(small)), ///
    title("回归残差图") ///
    xtitle("拟合值") ytitle("残差") ///
    yline(0, lcolor(red))
graph export "../dataset/auto2_output/graphs/residual_plot.png", replace
drop residuals fitted

* 图10: 分位数-分位数图（Q-Q图）
qnorm price, ///
    title("价格Q-Q图") ///
    ytitle("价格") xtitle("理论分位数")
graph export "../dataset/auto2_output/graphs/qq_plot.png", replace

* 图11: 热力图风格的交叉表可视化
preserve
contract foreign size_category, freq(count)
reshape wide count, i(size_category) j(foreign)
graph bar count0 count1, over(size_category) ///
    title("产地与车型大小交叉分布") ///
    legend(label(1 "国产") label(2 "进口")) ///
    ytitle("车辆数量")
graph export "../dataset/auto2_output/graphs/crosstab_visual.png", replace
restore

* 图12: 多面板图：按价格四分位数
twoway (scatter mpg weight), by(price_quartile, ///
    title("油耗与重量关系（按价格四分位数分组）")) ///
    ytitle("每加仑英里数") xtitle("重量 (磅)")
graph export "../dataset/auto2_output/graphs/mpg_weight_by_quartile.png", replace

/*------------------------------------------------------------------------------
  8. 生成结果表格
------------------------------------------------------------------------------*/

* 表1: 全面描述性统计表
preserve
quietly {
    tempname memhold
    postfile `memhold' str30 variable count mean sd min p25 p50 p75 max ///
        using "../dataset/auto2_output/tables/full_descriptive.dta", replace

    foreach var in price mpg weight length turn displacement gear_ratio {
        summarize `var', detail
        post `memhold' ("`var'") (r(N)) (r(mean)) (r(sd)) (r(min)) ///
            (r(p25)) (r(p50)) (r(p75)) (r(max))
    }
    postclose `memhold'
}

use "../dataset/auto2_output/tables/full_descriptive.dta", clear
export delimited using "../dataset/auto2_output/tables/full_descriptive.csv", replace

* 导出Excel格式
export excel using "../dataset/auto2_output/excel/full_descriptive.xlsx", ///
    firstrow(variables) replace

* 导出LaTeX格式
file open latextab using "../dataset/auto2_output/latex/full_descriptive.tex", write replace
file write latextab "\begin{table}[htbp]" _n
file write latextab "\centering" _n
file write latextab "\caption{全面描述性统计表\label{tab:full_desc}}" _n
file write latextab "\begin{tabular}{lrrrrrrrr}" _n
file write latextab "\toprule" _n
file write latextab "变量 & N & 均值 & 标准差 & 最小值 & 25\% & 50\% & 75\% & 最大值 \\" _n
file write latextab "\midrule" _n

local N = _N
forvalues i = 1/`N' {
    local var = variable[`i']
    local cnt = string(count[`i'], "%9.0f")
    local mn = string(mean[`i'], "%9.2f")
    local sd = string(sd[`i'], "%9.2f")
    local min = string(min[`i'], "%9.2f")
    local p25 = string(p25[`i'], "%9.2f")
    local p50 = string(p50[`i'], "%9.2f")
    local p75 = string(p75[`i'], "%9.2f")
    local max = string(max[`i'], "%9.2f")
    file write latextab "`var' & `cnt' & `mn' & `sd' & `min' & `p25' & `p50' & `p75' & `max' \\" _n
}

file write latextab "\bottomrule" _n
file write latextab "\end{tabular}" _n
file write latextab "\end{table}" _n
file close latextab
restore

* 表2: 按产地和车型大小的双向汇总表
preserve
collapse (mean) mean_price=price mean_mpg=mpg ///
         (sd) sd_price=price sd_mpg=mpg ///
         (count) n=price, by(foreign size_category)

export delimited using "../dataset/auto2_output/tables/summary_by_origin_size.csv", replace
export excel using "../dataset/auto2_output/excel/summary_by_origin_size.xlsx", ///
    firstrow(variables) replace

* LaTeX格式
file open latextab using "../dataset/auto2_output/latex/summary_by_origin_size.tex", write replace
file write latextab "\begin{table}[htbp]" _n
file write latextab "\centering" _n
file write latextab "\caption{按产地和车型大小分组的汇总统计\label{tab:summary_origin_size}}" _n
file write latextab "\begin{tabular}{llrrrrrr}" _n
file write latextab "\toprule" _n
file write latextab "产地 & 车型 & 平均价格 & 价格标准差 & 平均油耗 & 油耗标准差 & 样本量 \\" _n
file write latextab "\midrule" _n

local N = _N
forvalues i = 1/`N' {
    local fg = string(foreign[`i'], "%9.0f")
    local sz = string(size_category[`i'], "%9.0f")
    local mp = string(mean_price[`i'], "%9.2f")
    local sp = string(sd_price[`i'], "%9.2f")
    local mm = string(mean_mpg[`i'], "%9.2f")
    local sm = string(sd_mpg[`i'], "%9.2f")
    local n = string(n[`i'], "%9.0f")
    file write latextab "`fg' & `sz' & `mp' & `sp' & `mm' & `sm' & `n' \\" _n
}

file write latextab "\bottomrule" _n
file write latextab "\end{tabular}" _n
file write latextab "\end{table}" _n
file close latextab
restore

* 表3: T检验结果表
preserve
ttest price, by(foreign)
matrix ttest_results = r(mu_1), r(mu_2), r(t), r(p)

file open csvfile using "../dataset/auto2_output/tables/ttest_results.csv", write replace
file write csvfile "统计量,值" _n
file write csvfile "国产车平均价格," %9.2f (ttest_results[1,1]) _n
file write csvfile "进口车平均价格," %9.2f (ttest_results[1,2]) _n
file write csvfile "t统计量," %9.3f (ttest_results[1,3]) _n
file write csvfile "p值," %9.4f (ttest_results[1,4]) _n
file close csvfile

* LaTeX格式
file open latextab using "../dataset/auto2_output/latex/ttest_results.tex", write replace
file write latextab "\begin{table}[htbp]" _n
file write latextab "\centering" _n
file write latextab "\caption{价格T检验结果（国产vs进口）\label{tab:ttest}}" _n
file write latextab "\begin{tabular}{lr}" _n
file write latextab "\toprule" _n
file write latextab "统计量 & 值 \\" _n
file write latextab "\midrule" _n
file write latextab "国产车平均价格 & " %9.2f (ttest_results[1,1]) " \\" _n
file write latextab "进口车平均价格 & " %9.2f (ttest_results[1,2]) " \\" _n
file write latextab "t统计量 & " %9.3f (ttest_results[1,3]) " \\" _n
file write latextab "p值 & " %9.4f (ttest_results[1,4]) " \\" _n
file write latextab "\bottomrule" _n
file write latextab "\end{tabular}" _n
file write latextab "\end{table}" _n
file close latextab
restore

* 表4: 相关系数矩阵（扩展版）
preserve
correlate price mpg weight length turn displacement gear_ratio
matrix C = r(C)

* CSV格式
local vars "price mpg weight length turn displacement gear_ratio"
local nvars : word count `vars'

file open csvfile using "../dataset/auto2_output/tables/correlation_matrix.csv", write replace
file write csvfile "变量"
foreach var of local vars {
    file write csvfile ",`var'"
}
file write csvfile _n

forvalues i = 1/`nvars' {
    local var : word `i' of `vars'
    file write csvfile "`var'"
    forvalues j = 1/`nvars' {
        local val = string(C[`i',`j'], "%9.3f")
        file write csvfile ",`val'"
    }
    file write csvfile _n
}
file close csvfile

* Excel格式
putexcel set "../dataset/auto2_output/excel/correlation_matrix.xlsx", replace
putexcel A1 = "相关系数矩阵"
putexcel A2 = matrix(C), names

* LaTeX格式
file open latextab using "../dataset/auto2_output/latex/correlation_matrix.tex", write replace
file write latextab "\begin{table}[htbp]" _n
file write latextab "\centering" _n
file write latextab "\caption{相关系数矩阵\label{tab:correlation}}" _n
file write latextab "\begin{tabular}{l"
forvalues i = 1/`nvars' {
    file write latextab "r"
}
file write latextab "}" _n
file write latextab "\toprule" _n
file write latextab "变量"
foreach var of local vars {
    file write latextab " & `var'"
}
file write latextab " \\" _n
file write latextab "\midrule" _n

forvalues i = 1/`nvars' {
    local var : word `i' of `vars'
    file write latextab "`var'"
    forvalues j = 1/`nvars' {
        local val = string(C[`i',`j'], "%9.3f")
        file write latextab " & `val'"
    }
    file write latextab " \\" _n
}

file write latextab "\bottomrule" _n
file write latextab "\end{tabular}" _n
file write latextab "\end{table}" _n
file close latextab
restore

* 表5: 多模型回归结果对比表
* 运行所有回归模型
quietly regress price mpg
estimates store m1
quietly regress price mpg weight foreign
estimates store m2
quietly regress price mpg weight foreign displacement
estimates store m3
quietly regress log_price mpg weight foreign
estimates store m4

* 提取回归结果
preserve
clear
set obs 10

generate str30 variable = ""
generate coef1 = .
generate se1 = .
generate coef2 = .
generate se2 = .
generate coef3 = .
generate se3 = .
generate coef4 = .
generate se4 = .

* 填充变量名
replace variable = "mpg" in 1
replace variable = "weight" in 2
replace variable = "foreign" in 3
replace variable = "displacement" in 4
replace variable = "_cons" in 5
replace variable = "R-squared" in 6
replace variable = "Adj R-squared" in 7
replace variable = "N" in 8

* 模型1
estimates restore m1
matrix b1 = e(b)
matrix V1 = e(V)
replace coef1 = b1[1,1] in 1
replace se1 = sqrt(V1[1,1]) in 1
replace coef1 = b1[1,2] in 5
replace se1 = sqrt(V1[2,2]) in 5
replace coef1 = e(r2) in 6
replace coef1 = e(r2_a) in 7
replace coef1 = e(N) in 8

* 模型2
estimates restore m2
matrix b2 = e(b)
matrix V2 = e(V)
replace coef2 = b2[1,1] in 1
replace se2 = sqrt(V2[1,1]) in 1
replace coef2 = b2[1,2] in 2
replace se2 = sqrt(V2[2,2]) in 2
replace coef2 = b2[1,3] in 3
replace se2 = sqrt(V2[3,3]) in 3
replace coef2 = b2[1,4] in 5
replace se2 = sqrt(V2[4,4]) in 5
replace coef2 = e(r2) in 6
replace coef2 = e(r2_a) in 7
replace coef2 = e(N) in 8

* 模型3
estimates restore m3
matrix b3 = e(b)
matrix V3 = e(V)
replace coef3 = b3[1,1] in 1
replace se3 = sqrt(V3[1,1]) in 1
replace coef3 = b3[1,2] in 2
replace se3 = sqrt(V3[2,2]) in 2
replace coef3 = b3[1,3] in 3
replace se3 = sqrt(V3[3,3]) in 3
replace coef3 = b3[1,4] in 4
replace se3 = sqrt(V3[4,4]) in 4
replace coef3 = b3[1,5] in 5
replace se3 = sqrt(V3[5,5]) in 5
replace coef3 = e(r2) in 6
replace coef3 = e(r2_a) in 7
replace coef3 = e(N) in 8

* 模型4 (对数模型)
estimates restore m4
matrix b4 = e(b)
matrix V4 = e(V)
replace coef4 = b4[1,1] in 1
replace se4 = sqrt(V4[1,1]) in 1
replace coef4 = b4[1,2] in 2
replace se4 = sqrt(V4[2,2]) in 2
replace coef4 = b4[1,3] in 3
replace se4 = sqrt(V4[3,3]) in 3
replace coef4 = b4[1,4] in 5
replace se4 = sqrt(V4[4,4]) in 5
replace coef4 = e(r2) in 6
replace coef4 = e(r2_a) in 7
replace coef4 = e(N) in 8

* 导出CSV
export delimited using "../dataset/auto2_output/tables/regression_comparison.csv", replace

* 导出Excel
export excel using "../dataset/auto2_output/excel/regression_comparison.xlsx", ///
    firstrow(variables) replace

* 导出LaTeX
file open latextab using "../dataset/auto2_output/latex/regression_comparison.tex", write replace
file write latextab "\begin{table}[htbp]" _n
file write latextab "\centering" _n
file write latextab "\caption{多模型回归结果对比\label{tab:regression}}" _n
file write latextab "\begin{tabular}{lrrrrrrrr}" _n
file write latextab "\toprule" _n
file write latextab " & \multicolumn{2}{c}{模型1} & \multicolumn{2}{c}{模型2} & \multicolumn{2}{c}{模型3} & \multicolumn{2}{c}{模型4(log)} \\" _n
file write latextab "\cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule(lr){6-7} \cmidrule(lr){8-9}" _n
file write latextab "变量 & 系数 & 标准误 & 系数 & 标准误 & 系数 & 标准误 & 系数 & 标准误 \\" _n
file write latextab "\midrule" _n

forvalues i = 1/5 {
    local var = variable[`i']
    file write latextab "`var'"

    if !missing(coef1[`i']) {
        local c1 = string(coef1[`i'], "%9.3f")
        local s1 = string(se1[`i'], "%9.3f")
        file write latextab " & `c1' & `s1'"
    }
    else {
        file write latextab " & & "
    }

    if !missing(coef2[`i']) {
        local c2 = string(coef2[`i'], "%9.3f")
        local s2 = string(se2[`i'], "%9.3f")
        file write latextab " & `c2' & `s2'"
    }
    else {
        file write latextab " & & "
    }

    if !missing(coef3[`i']) {
        local c3 = string(coef3[`i'], "%9.3f")
        local s3 = string(se3[`i'], "%9.3f")
        file write latextab " & `c3' & `s3'"
    }
    else {
        file write latextab " & & "
    }

    if !missing(coef4[`i']) {
        local c4 = string(coef4[`i'], "%9.3f")
        local s4 = string(se4[`i'], "%9.3f")
        file write latextab " & `c4' & `s4'"
    }
    else {
        file write latextab " & & "
    }

    file write latextab " \\" _n
}

file write latextab "\midrule" _n

* R-squared行
forvalues i = 6/8 {
    local var = variable[`i']
    file write latextab "`var'"

    local c1 = string(coef1[`i'], "%9.3f")
    local c2 = string(coef2[`i'], "%9.3f")
    local c3 = string(coef3[`i'], "%9.3f")
    local c4 = string(coef4[`i'], "%9.3f")

    file write latextab " & \multicolumn{2}{c}{`c1'}"
    file write latextab " & \multicolumn{2}{c}{`c2'}"
    file write latextab " & \multicolumn{2}{c}{`c3'}"
    file write latextab " & \multicolumn{2}{c}{`c4'} \\" _n
}

file write latextab "\bottomrule" _n
file write latextab "\end{tabular}" _n
file write latextab "\end{table}" _n
file close latextab
restore

* 表6: 分位数回归结果对比
preserve
clear
set obs 6
generate str30 variable = ""
generate q25 = .
generate q50 = .
generate q75 = .

replace variable = "mpg" in 1
replace variable = "weight" in 2
replace variable = "foreign" in 3
replace variable = "_cons" in 4
replace variable = "Pseudo R2" in 5

estimates restore qreg25
matrix b25 = e(b)
replace q25 = b25[1,1] in 1
replace q25 = b25[1,2] in 2
replace q25 = b25[1,3] in 3
replace q25 = b25[1,4] in 4

estimates restore qreg50
matrix b50 = e(b)
replace q50 = b50[1,1] in 1
replace q50 = b50[1,2] in 2
replace q50 = b50[1,3] in 3
replace q50 = b50[1,4] in 4

estimates restore qreg75
matrix b75 = e(b)
replace q75 = b75[1,1] in 1
replace q75 = b75[1,2] in 2
replace q75 = b75[1,3] in 3
replace q75 = b75[1,4] in 4

export delimited using "../dataset/auto2_output/tables/quantile_regression.csv", replace
export excel using "../dataset/auto2_output/excel/quantile_regression.xlsx", ///
    firstrow(variables) replace

* LaTeX格式
file open latextab using "../dataset/auto2_output/latex/quantile_regression.tex", write replace
file write latextab "\begin{table}[htbp]" _n
file write latextab "\centering" _n
file write latextab "\caption{分位数回归结果\label{tab:qreg}}" _n
file write latextab "\begin{tabular}{lrrr}" _n
file write latextab "\toprule" _n
file write latextab "变量 & 25\%分位数 & 50\%分位数 & 75\%分位数 \\" _n
file write latextab "\midrule" _n

forvalues i = 1/4 {
    local var = variable[`i']
    local v25 = string(q25[`i'], "%9.3f")
    local v50 = string(q50[`i'], "%9.3f")
    local v75 = string(q75[`i'], "%9.3f")
    file write latextab "`var' & `v25' & `v50' & `v75' \\" _n
}

file write latextab "\bottomrule" _n
file write latextab "\end{tabular}" _n
file write latextab "\end{table}" _n
file close latextab
restore

/*------------------------------------------------------------------------------
  9. 生成LaTeX主文档
------------------------------------------------------------------------------*/
file open latexmain using "../dataset/auto2_output/latex/main_report.tex", write replace
file write latexmain "\documentclass[12pt,a4paper]{article}" _n
file write latexmain "\usepackage[utf8]{inputenc}" _n
file write latexmain "\usepackage[T1]{fontenc}" _n
file write latexmain "\usepackage{booktabs}" _n
file write latexmain "\usepackage{graphicx}" _n
file write latexmain "\usepackage{float}" _n
file write latexmain "\usepackage{caption}" _n
file write latexmain "\usepackage{subcaption}" _n
file write latexmain "\usepackage[margin=2.5cm]{geometry}" _n
file write latexmain "\usepackage{ctex}  % 支持中文" _n
file write latexmain "\usepackage{amsmath}" _n
file write latexmain "\usepackage{multirow}" _n
file write latexmain "" _n
file write latexmain "\title{Auto2数据集高级统计分析报告}" _n
file write latexmain "\author{Stata高级分析}" _n
file write latexmain "\date{\today}" _n
file write latexmain "" _n
file write latexmain "\begin{document}" _n
file write latexmain "" _n
file write latexmain "\maketitle" _n
file write latexmain "\tableofcontents" _n
file write latexmain "\newpage" _n
file write latexmain "" _n
file write latexmain "\section{数据概览}" _n
file write latexmain "本报告基于Stata内置的auto2数据集，包含74辆汽车的详细信息。" _n
file write latexmain "分析涵盖描述性统计、假设检验、相关性分析、回归分析等多个方面。" _n
file write latexmain "" _n
file write latexmain "\section{描述性统计}" _n
file write latexmain "\subsection{全面描述性统计}" _n
file write latexmain "\input{full_descriptive.tex}" _n
file write latexmain "" _n
file write latexmain "\subsection{分组统计}" _n
file write latexmain "\input{summary_by_origin_size.tex}" _n
file write latexmain "" _n
file write latexmain "\section{假设检验}" _n
file write latexmain "\subsection{T检验结果}" _n
file write latexmain "\input{ttest_results.tex}" _n
file write latexmain "" _n
file write latexmain "\section{相关性分析}" _n
file write latexmain "\input{correlation_matrix.tex}" _n
file write latexmain "" _n
file write latexmain "\section{回归分析}" _n
file write latexmain "\subsection{多模型对比}" _n
file write latexmain "\input{regression_comparison.tex}" _n
file write latexmain "" _n
file write latexmain "\subsection{分位数回归}" _n
file write latexmain "\input{quantile_regression.tex}" _n
file write latexmain "" _n
file write latexmain "\section{可视化分析}" _n
file write latexmain "详见graphs目录中的12张分析图表。" _n
file write latexmain "" _n
file write latexmain "\end{document}" _n
file close latexmain

/*------------------------------------------------------------------------------
  10. 保存处理后的数据
------------------------------------------------------------------------------*/
save "../dataset/auto2_output/auto2_processed.dta", replace
export delimited using "../dataset/auto2_output/auto2_processed.csv", replace

/*------------------------------------------------------------------------------
  11. 生成分析摘要报告
------------------------------------------------------------------------------*/
file open summary using "../dataset/auto2_output/analysis_summary.txt", write replace
file write summary "========================================" _n
file write summary "Auto2数据集分析摘要报告" _n
file write summary "生成时间: $S_DATE $S_TIME" _n
file write summary "========================================" _n
file write summary "" _n
file write summary "一、数据基本信息" _n
file write summary "  - 观测数: 74" _n
file write summary "  - 变量数: " _N _n
file write summary "" _n
file write summary "二、生成的图表（12张）" _n
file write summary "  1. 价格核密度估计图" _n
file write summary "  2. 价格对数分布图" _n
file write summary "  3. 价格箱线图（按产地和车型）" _n
file write summary "  4. 散点图矩阵" _n
file write summary "  5. 油耗与重量分组散点图" _n
file write summary "  6. 价格四分位数条形图" _n
file write summary "  7. 维修记录堆叠条形图" _n
file write summary "  8. 价格与油耗拟合图（含置信区间）" _n
file write summary "  9. 回归残差图" _n
file write summary "  10. Q-Q图" _n
file write summary "  11. 交叉表可视化" _n
file write summary "  12. 多面板图" _n
file write summary "" _n
file write summary "三、生成的表格（6个）" _n
file write summary "  1. 全面描述性统计表" _n
file write summary "  2. 按产地和车型分组汇总表" _n
file write summary "  3. T检验结果表" _n
file write summary "  4. 相关系数矩阵" _n
file write summary "  5. 多模型回归对比表" _n
file write summary "  6. 分位数回归结果表" _n
file write summary "" _n
file write summary "四、输出格式" _n
file write summary "  - CSV格式: tables/" _n
file write summary "  - Excel格式: excel/" _n
file write summary "  - LaTeX格式: latex/" _n
file write summary "  - 图表: graphs/" _n
file write summary "" _n
file write summary "五、LaTeX编译" _n
file write summary "  进入latex目录，运行:" _n
file write summary "  xelatex main_report.tex" _n
file write summary "" _n
file write summary "========================================" _n
file close summary

/*------------------------------------------------------------------------------
  结束
------------------------------------------------------------------------------*/
log close

display ""
display "=========================================="
display "Auto2数据集分析完成！"
display "=========================================="
display ""
display "输出目录: ../dataset/auto2_output/"
display ""
display "📊 图表文件（12张PNG）:"
display "  graphs/price_kdensity.png"
display "  graphs/log_price_hist.png"
display "  graphs/price_box_detailed.png"
display "  graphs/scatter_matrix.png"
display "  graphs/mpg_weight_grouped.png"
display "  graphs/price_quartile_bar.png"
display "  graphs/repair_stacked.png"
display "  graphs/price_mpg_ci.png"
display "  graphs/residual_plot.png"
display "  graphs/qq_plot.png"
display "  graphs/crosstab_visual.png"
display "  graphs/mpg_weight_by_quartile.png"
display ""
display "📋 表格文件（6个）:"
display "  CSV格式 (tables/):"
display "    - full_descriptive.csv"
display "    - summary_by_origin_size.csv"
display "    - ttest_results.csv"
display "    - correlation_matrix.csv"
display "    - regression_comparison.csv"
display "    - quantile_regression.csv"
display ""
display "  Excel格式 (excel/):"
display "    - full_descriptive.xlsx"
display "    - summary_by_origin_size.xlsx"
display "    - correlation_matrix.xlsx"
display "    - regression_comparison.xlsx"
display "    - quantile_regression.xlsx"
display ""
display "  LaTeX格式 (latex/):"
display "    - full_descriptive.tex"
display "    - summary_by_origin_size.tex"
display "    - ttest_results.tex"
display "    - correlation_matrix.tex"
display "    - regression_comparison.tex"
display "    - quantile_regression.tex"
display "    - main_report.tex (主文档)"
display ""
display "📄 其他文件:"
display "  - auto2_processed.dta (处理后的数据)"
display "  - auto2_processed.csv"
display "  - analysis_summary.txt (分析摘要)"
display ""
display "📖 LaTeX编译说明:"
display "  cd ../dataset/auto2_output/latex"
display "  xelatex main_report.tex"
display ""
display "=========================================="

/*==============================================================================
  脚本说明：

  本脚本使用auto2数据集进行全面的统计分析，包括：

  1. 数据清理和变量工程
     - 缺失值处理
     - 生成8个新变量（对数、分类、指标等）

  2. 描述性统计
     - 全样本统计
     - 多维度分组统计

  3. 高级统计分析
     - T检验
     - 方差分析
     - 卡方检验
     - 相关性分析
     - 分位数回归

  4. 回归分析
     - 简单线性回归
     - 多元回归
     - 交互项回归
     - 对数回归
     - 稳健标准误回归

  5. 可视化（12张图表）
     - 核密度估计
     - 箱线图
     - 散点图矩阵
     - 分组散点图
     - 残差图
     - Q-Q图
     - 多面板图等

  6. 多格式输出
     - CSV格式（6个表格）
     - Excel格式（5个表格）
     - LaTeX格式（6个表格 + 主文档）
     - PNG图表（12张）

  运行方式：
  do do/auto2_analysis.do

  特点：
  - 无需安装额外包，使用Stata内置命令
  - 完整的LaTeX文档，可直接编译
  - 多种格式输出，便于不同用途
  - 详细的分析摘要报告
==============================================================================*/

